package org.numb.concurrency.chapter03;

import java.sql.SQLOutput;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class InterruptLock {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
                // 持有锁后保持10s
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    System.out.println("thread 1 is interrupted");
                }
            } catch (InterruptedException e) {
                // 线程被打断
                System.out.println("thread 1 is interrupted");
            } finally {
                // 必须释放锁，否则thread2 仍然无法获取锁
                lock.unlock();
                System.out.println("release lock in thread 1");
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread 2 get lock");
            lock.unlock();
        });
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        t2.start();
        TimeUnit.SECONDS.sleep(1);
        t1.interrupt();
    }

}
